package com.example.stuwork.controller;

import com.example.stuwork.common.Result;
import com.example.stuwork.pojo.Quiz;
import com.example.stuwork.pojo.QuizQuestion;
import com.example.stuwork.pojo.QuizSubmission;
import com.example.stuwork.service.QuizQuestionService;
import com.example.stuwork.service.QuizService;
import com.example.stuwork.service.QuizSubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 随堂测试控制器
 */
@RestController
@RequestMapping("/quiz")
public class QuizController {

    @Autowired
    private QuizService quizService;
    
    @Autowired
    private QuizQuestionService quizQuestionService;
    
    @Autowired
    private QuizSubmissionService quizSubmissionService;

    /**
     * 创建测试
     *
     * @param params 包含测试信息和题目列表的参数
     * @return 创建结果
     */
    @PostMapping("/create")
    public Result<?> createQuiz(@RequestBody Map<String, Object> params) {
        try {
            Quiz quiz = new Quiz();
            quiz.setCourseId((String) params.get("courseId"));
            quiz.setClassId(Long.valueOf(params.get("classId").toString()));
            quiz.setTeacherId((String) params.get("teacherId"));
            quiz.setTitle((String) params.get("title"));
            quiz.setDescription((String) params.get("description"));
            
            String questions = params.containsKey("questions") ? params.get("questions").toString() : null;
            
            return quizService.createQuiz(quiz, questions);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建测试失败: " + e.getMessage());
        }
    }

    /**
     * 获取测试列表
     *
     * @return 测试列表
     */
    @GetMapping("/list")
    public Result<List<Quiz>> getQuizList() {
        return quizService.getQuizList();
    }

    /**
     * 根据教师ID获取测试列表
     *
     * @param teacherId 教师ID
     * @return 测试列表
     */
    @GetMapping("/teacher/{teacherId}")
    public Result<List<Quiz>> getQuizByTeacher(@PathVariable String teacherId) {
        return quizService.getQuizByTeacher(teacherId);
    }

    /**
     * 根据课程ID和班级ID获取测试列表
     *
     * @param courseId 课程ID
     * @param classId 班级ID
     * @return 测试列表
     */
    @GetMapping("/course")
    public Result<List<Quiz>> getQuizByCourseAndClass(
            @RequestParam String courseId, 
            @RequestParam Long classId) {
        return quizService.getQuizByCourseAndClass(courseId, classId);
    }

    /**
     * 获取学生可参与的测试列表
     *
     * @param courseId 课程ID
     * @param classId 班级ID
     * @param studentId 学生ID
     * @return 测试列表
     */
    @GetMapping("/student/list")
    public Result<List<Map<String, Object>>> getStudentQuizList(
            @RequestParam String courseId, 
            @RequestParam Long classId,
            @RequestParam String studentId) {
        return quizService.getStudentQuizList(courseId, classId, studentId);
    }

    /**
     * 获取测试详情
     *
     * @param quizId 测试ID
     * @return 测试详情
     */
    @GetMapping("/detail/{quizId}")
    public Result<Map<String, Object>> getQuizDetail(@PathVariable Long quizId) {
        return quizService.getQuizDetail(quizId);
    }

    /**
     * 开始测试
     *
     * @param quizId 测试ID
     * @return 开始结果
     */
    @PutMapping("/start/{quizId}")
    public Result<?> startQuiz(@PathVariable Long quizId) {
        return quizService.startQuiz(quizId);
    }

    /**
     * 结束测试
     *
     * @param quizId 测试ID
     * @return 结束结果
     */
    @PutMapping("/end/{quizId}")
    public Result<?> endQuiz(@PathVariable Long quizId) {
        return quizService.endQuiz(quizId);
    }

    /**
     * 删除测试
     *
     * @param quizId 测试ID
     * @return 删除结果
     */
    @DeleteMapping("/{quizId}")
    public Result<?> deleteQuiz(@PathVariable Long quizId) {
        return quizService.deleteQuiz(quizId);
    }

    /**
     * 根据测试ID获取题目列表
     *
     * @param quizId 测试ID
     * @return 题目列表
     */
    @GetMapping("/questions/{quizId}")
    public Result<List<QuizQuestion>> getQuestionsByQuizId(@PathVariable Long quizId) {
        return quizQuestionService.getQuestionsByQuizId(quizId);
    }

    /**
     * 添加题目
     *
     * @param question 题目信息
     * @return 添加结果
     */
    @PostMapping("/question/add")
    public Result<?> addQuestion(@RequestBody QuizQuestion question) {
        return quizQuestionService.addQuestion(question);
    }

    /**
     * 删除题目
     *
     * @param questionId 题目ID
     * @return 删除结果
     */
    @DeleteMapping("/question/{questionId}")
    public Result<?> deleteQuestion(@PathVariable Long questionId) {
        return quizQuestionService.deleteQuestion(questionId);
    }

    /**
     * 提交测试答案
     *
     * @param params 提交参数
     * @return 提交结果
     */
    @PostMapping("/submit")
    public Result<?> submitQuiz(@RequestBody Map<String, Object> params) {
        try {
            Long quizId = Long.valueOf(params.get("quizId").toString());
            String studentId = (String) params.get("studentId");
            String answers = params.containsKey("answers") ? params.get("answers").toString() : "{}";
            
            // 获取前端计算的分数
            Integer score = null;
            if (params.containsKey("score")) {
                score = Integer.valueOf(params.get("score").toString());
            }
            
            QuizSubmission submission = new QuizSubmission(quizId, studentId, answers);
            
            // 如果前端提供了分数，直接使用
            if (score != null) {
                submission.setScore(score);
            }
            
            return quizSubmissionService.submitQuiz(submission);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提交答案失败: " + e.getMessage());
        }
    }

    /**
     * 获取测试的提交列表
     *
     * @param quizId 测试ID
     * @return 提交列表
     */
    @GetMapping("/submissions/{quizId}")
    public Result<List<QuizSubmission>> getSubmissionsByQuizId(@PathVariable Long quizId) {
        return quizSubmissionService.getSubmissionsByQuizId(quizId);
    }

    /**
     * 获取学生的测试提交记录
     *
     * @param quizId 测试ID
     * @param studentId 学生ID
     * @return 提交记录
     */
    @GetMapping("/student/submission")
    public Result<QuizSubmission> getStudentSubmission(
            @RequestParam Long quizId,
            @RequestParam String studentId) {
        return quizSubmissionService.getStudentSubmission(quizId, studentId);
    }

    /**
     * 获取测试统计信息
     *
     * @param quizId 测试ID
     * @return 统计信息
     */
    @GetMapping("/stats/{quizId}")
    public Result<Map<String, Object>> getQuizStats(@PathVariable Long quizId) {
        return quizSubmissionService.getQuizStats(quizId);
    }
    
    /**
     * 检查学生是否已提交测试
     *
     * @param quizId 测试ID
     * @param studentId 学生ID
     * @return 是否已提交
     */
    @GetMapping("/submitted")
    public Result<Boolean> isSubmitted(
            @RequestParam Long quizId,
            @RequestParam String studentId) {
        return quizSubmissionService.isSubmitted(quizId, studentId);
    }
} 